// FaceD.cpp : 
//////////////////////////////////////////////////////
// 人脸检测C++版本
// Editor:LinJM
//////////////////////////////////////////////////////

#include <cstdio>
#include <cstdlib>
#include <Windows.h>
#include <vector>
#include <iostream>
#include <string>

#include <opencv2\opencv.hpp>

using namespace std;
using namespace cv;

int main(int argc, char* argv[])
{

	//加载Haar特征检测分类器
	const string CascadeFileName = "D:\\opencv\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml";
	CascadeClassifier cascade = CascadeClassifier::CascadeClassifier(CascadeFileName);

	// 载入图像
	const string pstrImageName = "E:\\1.png";
	VideoCapture vc0(0);
	while (1){
		Mat s, SrcImage, s2, s3;
		vc0 >> SrcImage;

		Mat GrayImage;

		cvtColor(SrcImage, GrayImage, CV_BGR2GRAY);

		// 人脸识别与标记
		if (!cascade.empty())
		{
			CvScalar FaceCirclecolors[] =
			{
				CvScalar(0, 0, 255),
				CvScalar(0, 128, 255),
				CvScalar(0, 255, 255),
				CvScalar(0, 255, 0),
				CvScalar(255, 128, 0),
				CvScalar(255, 255, 0),
				CvScalar(255, 0, 0),
				CvScalar(255, 0, 255)
			};

			vector<cv::Rect> faces;

			DWORD dwTimeBegin, dwTimeEnd;
			dwTimeBegin = GetTickCount();
			// 识别
			cascade.detectMultiScale(GrayImage, faces);
			dwTimeEnd = GetTickCount();

			cout << "人脸个数:" << faces.end() - faces.begin()
				<< "识别用时:" << dwTimeEnd - dwTimeBegin << "ms\n";
			// 标记
			int n = 0;
			for (vector<cv::Rect>::const_iterator i = faces.begin(); i < faces.end(); i++, n++)
			{
				Point center;
				int radius;
				center.x = cvRound((i->x + i->width * 0.5));
				center.y = cvRound((i->y + i->height * 0.5));
				radius = cvRound((i->width + i->height) * 0.25);
				circle(SrcImage, center, radius, FaceCirclecolors[n % 8], 2);
			}
		}
		namedWindow("人脸识别");
		imshow("人脸识别", SrcImage);
		waitKey(100);
	}

	return 0;
}